package com.laihui.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.laihui.MyApplication;
import com.laihui.base.BaseActivity;
import com.laihui.entity.Account;
import com.laihui.entity.LoanBean;
import com.laihui.entity.LoanItem;
import com.laihui.entity.MemberBank;
import com.laihui.entity.RealBean;
import com.laihui.entity.RedPacketList;
import com.laihui.entity.RetMap;
import com.laihui.utils.ToastUtil;
import com.laihui.view.TopBar;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class InvestActivity extends BaseActivity {
    @BindView(R.id.topbar)
    TopBar topbar;

    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_recharge)
    TextView tvRecharge;
    @BindView(R.id.et_invest_money)
    EditText etInvestMoney;
    @BindView(R.id.tv_discount_coupon)
    TextView tvDiscountCoupon;
    @BindView(R.id.ll_discount_coupon)
    LinearLayout llDiscountCoupon;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.tv_earnings)
    TextView tvEarning;
    @BindView(R.
            id.btn_submit)
    Button btnSubmit;
    @BindView(R.id.tv_forget_password)
    TextView tvForgetPassword;

    @BindView(R.id.tv_wait_tender)
    TextView wait_tender;
    @BindView(R.id.tv_apr)
    TextView tv_apr;
    @BindView(R.id.tv_loan_lowest_account)
    TextView lowest_account;


    private static boolean isRealName = false ;//是否实名认证的标志
    private static boolean isBindBankCard = false ;//是否绑定银行卡的标志


    private Activity mActivity;
    private MyApplication application;
    private static final String TAG = "InvestActivity";
    private DecimalFormat df = new DecimalFormat("0.00");
    LoanBean loanbean;

    private static int SELECT_REDPACKET = 1;

    //是否实名认证
    private void isReal() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", application.userId);
        application.apiService.toReal(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RealBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(RealBean toRealname) {

                        if (toRealname.item!=null) {
                            isRealName = true;
                        } else {
                            isRealName = false;
                        }
                    }
                });
    }

    //是否绑定银行卡
    private void isBind() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", application.userId);
        application.apiService.isBankBind(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MemberBank>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(MemberBank bankCard) {
                        if (bankCard.item!=null) {
                            isBindBankCard = true;
                        } else {
                            isBindBankCard = false;
                        }
                    }
                });
    }

    @Override
    public void init() {
        mActivity = InvestActivity.this;
        application = (MyApplication) getApplication();
        loanbean = (LoanBean) getIntent().getSerializableExtra("loan");
        topbar.setOnTopbarClickListener(new TopBar.topbarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });

        etInvestMoney.setHint(loanbean.min_account+"元起投");
        loadData();

        isBind();
        initViewPager();
    }


    private void initViewPager() {
        HashMap map = new HashMap();
        map.put("loanId",loanbean.id+"");
        application.apiService.loanDetail(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoanItem>() {
                    @Override
                    public void onCompleted() {

                    }
                    @Override
                    public void onError(Throwable e) {
                        Log.e("Index3Fragment", "onError: " + e.toString());
                    }

                    @Override
                    public void onNext(LoanItem loanItem) {
                        tv_apr.setText(loanItem.item.apr+"");
                        wait_tender.setText(Double.parseDouble(loanItem.item.account)-Double.parseDouble(loanItem.item.amount_invested)+"");
                        lowest_account.setText(loanItem.item.min_account+"起投");
                        loanbean = loanItem.item;
                    }
                });
    }




    /**
     * 红包Id
     */
    private String userRedId = "";
    RedPacketList.RedPacket red;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == SELECT_REDPACKET) {
            if (resultCode == RESULT_OK) {
                red = (RedPacketList.RedPacket) data.getSerializableExtra("red");
                if(red!=null){
                    tvDiscountCoupon.setText("满"+red.tender_limit+"减"+red.money);
                }else{
                    tvDiscountCoupon.setText(/*investDetail.getUserRedNum()+*/"不使用红包");
                }


//
//                InvestDetail.RedsBean userRedsBean = null;
//                Bundle bundle = data.getExtras();
//                String jsonData = bundle.getString("red");
//
//                if (!jsonData.equals("")) {
//                    userRedsBean = new Gson().fromJson(jsonData, InvestDetail.RedsBean.class);
//                    userRedId = userRedsBean.getId() + "";
//                } else {
//                    userRedId = "-1";
//                }
//                if (userRedsBean == null) {
//                    tvDiscountCoupon.setText(/*investDetail.getUserRedNum()+*/"不使用红包");
//
//                } else {
//
//                    if (userRedsBean.getRed_type_id() == 1) {
//
//                        tvDiscountCoupon.setText(userRedsBean.getRed_title()+"加息券");
//                    } else if (userRedsBean.getRed_type_id() == 2) {
//                        tvDiscountCoupon.setText(userRedsBean.getRed_title()+"抵扣券");
//
//                    }
//                }


            }

        }
    }



    private void tender() {
        String userId = application.userId;
        String account = etInvestMoney.getText().toString();

        String payPassword = etPassword.getText().toString();


        if (TextUtils.isEmpty(account)) {
            ToastUtil.showToast(mActivity, "请输入投资金额");
            return;
        }
        if (TextUtils.isEmpty(payPassword)) {
            ToastUtil.showToast(mActivity, "请输入交易密码");
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("member_id", userId);
        map.put("account", account);
        map.put("payPassword", payPassword);
        map.put("loanId", loanbean.id+"");
        if(red!=null){
            map.put("packet_id", red.id+"");
        }
        showProgress();
        application.apiService.doTender(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RetMap>() {
                    @Override
                    public void onCompleted() {
                        dismissProgress();
                    }
                    @Override
                    public void onError(Throwable e) {
                        dismissProgress();
                        Log.e("Index3Fragment", "onError: " + e.toString());
                    }
                    @Override
                    public void onNext(RetMap retMap) {
                        dismissProgress();
                        ToastUtil.showToast(InvestActivity.this,retMap.message);
                        if(retMap.status.equals("1")){

                            finish();
                        }
                    }
                });


    }
    //如果登录的话这些显示出来
    private void loadData() {
        if (application.isLogin) {
            Map<String, String> map = new HashMap<>();
            map.put("member_id", String.valueOf(application.userId) + "");
            //加载总资产，累计收益，代收收益，头像旁边的手机号
            application.apiService.getAccount(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Account>() {
                        @Override
                        public void onCompleted() {

                        }
                        @Override
                        public void onError(Throwable e) {
                            Log.e("Index3Fragment", "onError: " + e.toString());
                        }
                        @Override
                        public void onNext(Account account) {
                            tvTotalMoney.setText(account.item.balance+"");
                        }
                    });
        }else{
            startActivity(new Intent(mActivity, LoginActivity.class));
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_invest;
    }

    @Override
    public Activity bindActivity() {
        return this;
    }


    @OnClick({R.id.ll_discount_coupon, R.id.btn_submit, R.id.tv_recharge,R.id.tv_forget_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_discount_coupon://跳转选择红包页面
                Intent intent = new Intent(mActivity, SelectRedPacketActivity.class);
                intent.putExtra("loan",loanbean);
                startActivityForResult(intent, SELECT_REDPACKET);
                break;
            case R.id.tv_forget_password:
                startActivity(new Intent(mActivity,ForgetDealPasswordActivity.class));
                break;

            case R.id.tv_recharge:
                Map<String, String> map2 = new HashMap<>();
                map2.put("member_id", application.userId);
                if(!isBindBankCard){
                    ToastUtil.showToast(mActivity, "您尚未绑定银行卡");
                }else{
                    startActivity(new Intent(mActivity, RechargeActivity.class));
                }

                break;
            case R.id.btn_submit:
                tender();
                break;
        }
    }


}
